{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "initial_id",
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    ""
   ]
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# PromptTemplate的使用\n",
    "\n",
    "1、PromptTemplate如何获取实例  (掌握，两种方式)\n",
    "\n",
    "2、两种特殊结构的使用 （部分提示词模板的使用(掌握)、组合提示词的使用）\n",
    "\n",
    "3、给变量赋值的两种方式(掌握)：format() / invoke()\n",
    "\n",
    "4、结合大模型的使用\n",
    "\n",
    "## 1、PromptTemplate如何获取实例\n",
    "\n",
    "方式1：使用构造方法的方式\n"
   ],
   "id": "2df1693fc6280dad"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T06:47:49.555484Z",
     "start_time": "2025-08-23T06:47:49.523602Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.prompts import PromptTemplate\n",
    "\n",
    "#1、创建PromptTemplate的实例\n",
    "#参数中必须要指明：input_variables 、template\n",
    "prompt_template = PromptTemplate(\n",
    "    template=\"你是一个{role},你的名字叫{name}\",\n",
    "    input_variables=[\"role\",\"name\"],\n",
    ")\n",
    "\n",
    "# print(prompt_template)\n",
    "\n",
    "\n",
    "#2、填充实例中的变量。暂且使用format()\n",
    "prompt = prompt_template.format(role=\"人工智能专家\",name=\"小智\")\n",
    "\n",
    "print(prompt)\n",
    "\n"
   ],
   "id": "cb1ac354a51923d5",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你是一个人工智能专家,你的名字叫小智\n"
     ]
    }
   ],
   "execution_count": 2
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T06:48:55.205359Z",
     "start_time": "2025-08-23T06:48:55.130586Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "#定义多变量模板\n",
    "template = PromptTemplate(\n",
    "    template=\"请评价{product}的优缺点，包括{aspect1}和{aspect2}。\",\n",
    "    input_variables=[\"product\", \"aspect1\", \"aspect2\"])\n",
    "\n",
    "#使用模板生成提示词\n",
    "prompt_1 = template.format(product=\"智能手机\", aspect1=\"电池续航\", aspect2=\"拍照质量\")\n",
    "prompt_2 = template.format(product=\"笔记本电脑\", aspect1=\"处理速度\", aspect2=\"便携性\")\n",
    "\n",
    "print(\"提示词1:\",prompt_1)\n",
    "print(\"提示词2:\",prompt_2)"
   ],
   "id": "3bff825a3764e4d7",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "提示词1: 请评价智能手机的优缺点，包括电池续航和拍照质量。\n",
      "提示词2: 请评价笔记本电脑的优缺点，包括处理速度和便携性。\n"
     ]
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "方式2：from_template() : 推荐！！",
   "id": "fad32f9ea9a22e62"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T06:51:24.574410Z",
     "start_time": "2025-08-23T06:51:24.557408Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.prompts import PromptTemplate\n",
    "\n",
    "\n",
    "#1、创建PromptTemplate的实例\n",
    "prompt_template = PromptTemplate.from_template(template=\"你是一个{role},你的名字叫{name}\")\n",
    "\n",
    "# print(prompt_template)\n",
    "\n",
    "\n",
    "#2、填充实例中的变量。暂且使用format()\n",
    "prompt = prompt_template.format(role=\"人工智能专家\",name=\"小智\")\n",
    "\n",
    "print(prompt)\n"
   ],
   "id": "c8cb6951cd6f7d09",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你是一个人工智能专家,你的名字叫小智\n"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T06:51:57.748042Z",
     "start_time": "2025-08-23T06:51:57.733614Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "#定义多变量模板\n",
    "template = PromptTemplate.from_template(template=\"请评价{product}的优缺点，包括{aspect1}和{aspect2}。\")\n",
    "\n",
    "#使用模板生成提示词\n",
    "prompt_1 = template.format(product=\"智能手机\", aspect1=\"电池续航\", aspect2=\"拍照质量\")\n",
    "\n",
    "print(prompt_1)"
   ],
   "id": "11e0bb0ed5818074",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请评价智能手机的优缺点，包括电池续航和拍照质量。\n"
     ]
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "如果提示词模板中不包含变量，则调用format()时，不需要传入参数！",
   "id": "bee61d9f3e856d62"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T06:52:36.205703Z",
     "start_time": "2025-08-23T06:52:36.192630Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#1.导入相关的包\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "\n",
    "# 2.定义提示词模版对象\n",
    "text = \"\"\"\n",
    "Tell me a joke\n",
    "\"\"\"\n",
    "\n",
    "prompt_template = PromptTemplate.from_template(text)\n",
    "# 3.默认使用f-string进行格式化（返回格式好的字符串）\n",
    "prompt = prompt_template.format()\n",
    "print(prompt)"
   ],
   "id": "66224073a212cc3",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Tell me a joke\n",
      "\n"
     ]
    }
   ],
   "execution_count": 6
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## 2、 两种特殊结构的使用 （部分提示词模板的使用、组合提示词的使用）\n",
    "\n",
    "### 2.1 部分提示词模板的使用（重点）\n",
    "\n",
    "方式1： 在PromptTemplate的构造方法或from_template()方法内，使用partial_variables设置\n"
   ],
   "id": "682716cbd054ac4f"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T06:56:40.201007Z",
     "start_time": "2025-08-23T06:56:40.193693Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "#定义多变量模板\n",
    "template = PromptTemplate.from_template(\n",
    "    template=\"请评价{product}的优缺点，包括{aspect1}和{aspect2}。\",\n",
    "    partial_variables={\"aspect1\":\"电池续航\"}\n",
    ")\n",
    "\n",
    "#使用模板生成提示词\n",
    "prompt_1 = template.format(product=\"智能手机\",aspect2=\"拍照质量\")\n",
    "\n",
    "print(prompt_1)"
   ],
   "id": "ce23916bdad95757",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请评价智能手机的优缺点，包括电池续航和拍照质量。\n"
     ]
    }
   ],
   "execution_count": 7
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T06:58:55.108976Z",
     "start_time": "2025-08-23T06:58:55.096879Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "#定义多变量模板\n",
    "template = PromptTemplate(\n",
    "    template=\"请评价{product}的优缺点，包括{aspect1}和{aspect2}。\",\n",
    "    input_variables=[\"product\", \"aspect1\", \"aspect2\"],\n",
    "    partial_variables={\"aspect1\":\"电池续航\",\"aspect2\":\"拍照质量\"}\n",
    ")\n",
    "\n",
    "#使用模板生成提示词\n",
    "prompt_1 = template.format(product=\"智能手机\")\n",
    "\n",
    "print(\"提示词1:\",prompt_1)"
   ],
   "id": "4c16215f122c8df2",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "提示词1: 请评价智能手机的优缺点，包括电池续航和拍照质量。\n"
     ]
    }
   ],
   "execution_count": 9
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "方式2：调用方法partial()",
   "id": "79dc7c7b0e8fb240"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T07:02:28.282794Z",
     "start_time": "2025-08-23T07:02:28.266848Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "#定义多变量模板\n",
    "template = PromptTemplate(\n",
    "    template=\"请评价{product}的优缺点，包括{aspect1}和{aspect2}。\",\n",
    "    input_variables=[\"product\", \"aspect1\", \"aspect2\"],\n",
    "    # partial_variables={\"aspect1\":\"电池续航\",\"aspect2\":\"拍照质量\"}\n",
    ")\n",
    "\n",
    "# partial()调用完以后，不会对调用者这个模板对象产生影响；而其返回值是一个新的模板\n",
    "template1 = template.partial(aspect1=\"电池续航\",aspect2=\"拍照质量\")\n",
    "\n",
    "#使用模板生成提示词\n",
    "prompt_1 = template1.format(product=\"智能手机\")\n",
    "\n",
    "print(\"提示词1:\",prompt_1)"
   ],
   "id": "74450df982fd69cf",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "提示词1: 请评价智能手机的优缺点，包括电池续航和拍照质量。\n"
     ]
    }
   ],
   "execution_count": 13
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "#定义多变量模板\n",
    "template = PromptTemplate(\n",
    "    template=\"请评价{product}的优缺点，包括{aspect1}和{aspect2}。\",\n",
    "    input_variables=[\"product\", \"aspect1\", \"aspect2\"],\n",
    ").partial(aspect1=\"电池续航\",aspect2=\"拍照质量\")\n",
    "\n",
    "#使用模板生成提示词\n",
    "prompt_1 = template.format(product=\"智能手机\")\n",
    "\n",
    "print(\"提示词1:\",prompt_1)"
   ],
   "id": "9e42bb3ac0c94bb1"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T07:05:05.768029Z",
     "start_time": "2025-08-23T07:05:05.750490Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "#定义多变量模板\n",
    "template = (PromptTemplate\n",
    "            .from_template(template=\"请评价{product}的优缺点，包括{aspect1}和{aspect2}。\")\n",
    "            .partial(aspect1=\"电池续航\",aspect2=\"拍照质量\"))\n",
    "\n",
    "#使用模板生成提示词\n",
    "prompt_1 = template.format(product=\"智能手机\")\n",
    "\n",
    "print(\"提示词1:\",prompt_1)"
   ],
   "id": "98f10aa4c8125d86",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "提示词1: 请评价智能手机的优缺点，包括电池续航和拍照质量。\n"
     ]
    }
   ],
   "execution_count": 14
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "### 2.2 组合提示词的使用（了解）\n",
    "\n"
   ],
   "id": "f0d0f22d74ec5f9f"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "from langchain_core.prompts import PromptTemplate\n",
    "\n",
    "template = (\n",
    "    PromptTemplate.from_template(template = \"Tell me a joke about {topic}\")\n",
    "    + \", make it funny\"\n",
    "    + \"\\n\\nand in {language}\"\n",
    ")\n",
    "\n",
    "prompt = template.format(topic=\"sports\", language=\"spanish\")\n",
    "print(prompt)"
   ],
   "id": "ddb452aefc917d2a"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## 3、给变量赋值的两种方式：format() / invoke()\n",
    "\n",
    "format() : 参数部分：给变量赋值;     返回值：str类型\n",
    "\n",
    "invoke() : 参数部分：使用的是字典;     返回值：PromptValue类型   ---推荐！\n",
    "\n",
    "\n",
    "举例：调用format()"
   ],
   "id": "fb578fee25b8032d"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T07:10:46.673031Z",
     "start_time": "2025-08-23T07:10:46.666258Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "#定义多变量模板\n",
    "template = PromptTemplate.from_template(\n",
    "    template=\"请评价{product}的优缺点，包括{aspect1}和{aspect2}。\")\n",
    "\n",
    "#使用模板生成提示词\n",
    "prompt_1 = template.format(product=\"智能手机\", aspect1=\"电池续航\", aspect2=\"拍照质量\")\n",
    "\n",
    "print(prompt_1)\n",
    "print(type(prompt_1))"
   ],
   "id": "a4ba811282da15cd",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请评价智能手机的优缺点，包括电池续航和拍照质量。\n",
      "<class 'str'>\n"
     ]
    }
   ],
   "execution_count": 15
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例：调用invoke()",
   "id": "efd77fbb860871f"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T07:12:31.253496Z",
     "start_time": "2025-08-23T07:12:30.945610Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "#定义多变量模板\n",
    "template = PromptTemplate.from_template(\n",
    "    template=\"请评价{product}的优缺点，包括{aspect1}和{aspect2}。\")\n",
    "\n",
    "#使用模板生成提示词\n",
    "# prompt_1 = template.format(product=\"智能手机\", aspect1=\"电池续航\", aspect2=\"拍照质量\")\n",
    "prompt_1 = template.invoke(input={\"product\":\"智能手机\",\"aspect1\":\"电池续航\",\"aspect2\":\"拍照质量\"})\n",
    "\n",
    "print(prompt_1)\n",
    "print(type(prompt_1))  #返回值类型：PromptValue"
   ],
   "id": "5e9758198b430785",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "text='请评价智能手机的优缺点，包括电池续航和拍照质量。'\n",
      "<class 'langchain_core.prompt_values.StringPromptValue'>\n"
     ]
    }
   ],
   "execution_count": 16
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 4、结合大模型的使用\n",
   "id": "e2f12f26489f2c06"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T07:17:39.074024Z",
     "start_time": "2025-08-23T07:17:31.883867Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "import os\n",
    "import dotenv\n",
    "\n",
    "#加载配置文件\n",
    "dotenv.load_dotenv()\n",
    "\n",
    "\n",
    "os.environ[\"OPENAI_BASE_URL\"] = os.getenv(\"OPENAI_BASE_URL\")\n",
    "os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY1\")\n",
    "\n",
    "\n",
    "# 获取对话模型：\n",
    "chat_model = ChatOpenAI(\n",
    "    model=\"gpt-4o-mini\",\n",
    "    max_tokens=500\n",
    ")\n",
    "\n",
    "\n",
    "# 生成提示词模板\n",
    "template = PromptTemplate.from_template(\n",
    "    template=\"请评价{product}的优缺点，包括{aspect1}和{aspect2}。\")\n",
    "\n",
    "# 给模板的变量赋值\n",
    "prompt = template.invoke(input={\"product\":\"智能手机\",\"aspect1\":\"电池续航\",\"aspect2\":\"拍照质量\"})\n",
    "\n",
    "# 调用大模型，将提示词传入\n",
    "response= chat_model.invoke(prompt)\n",
    "print(response)\n",
    "print(type(response))"
   ],
   "id": "415caae2a803a9aa",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "content='智能手机在现代生活中扮演着重要角色，其优缺点各有千秋。\\n\\n### 优点\\n\\n1. **便携性**：智能手机小巧轻便，方便携带，可以随时随地进行通信、上网和娱乐。\\n  \\n2. **多功能性**：除了基本的通话功能，智能手机集成了相机、音乐播放器、导航仪和各种应用程序，满足用户的多种需求。\\n\\n3. **拍照质量**：现代智能手机的拍照功能越来越强大，许多手机配备高像素的摄像头和先进的图像处理技术，能够拍摄出高质量的照片和视频，适合日常记录和社交媒体分享。\\n\\n4. **电池续航**：虽然电池续航在不同型号间差异较大，但高端智能手机通常配备大容量电池和省电模式，可以支持一整天的使用。\\n\\n5. **互联网连接**：智能手机可以随时连接Wi-Fi或移动数据，方便用户进行信息查询和在线购物。\\n\\n### 缺点\\n\\n1. **电池续航**：尽管许多智能手机电池寿命较长，但高频率使用（如玩游戏、看视频）会迅速消耗电量，一些低端机型的续航表现则较差，需要频繁充电。\\n\\n2. **拍照质量**：虽然很多智能手机拍照效果优秀，但在低光环境下，成像质量可能受到影响。此外，专业摄影师可能觉得手机拍照无法替代专业相机。\\n\\n3. **依赖性**：智能手机的普及使人们对其产生较强的依赖，容易导致成瘾，影响人际关系和生活质量。\\n\\n4. **安全隐患**：智能手机存储大量个人信息，如果未采取适当的安全措施，可能面临隐私泄露的风险。\\n\\n5. **价格问题**：高端智能手机的价格较高，许多消费者在购买时面临经济压力。\\n\\n### 总结\\n\\n智能手机在便利性和多功能性上有着显著优势，但其电池续航和拍照质量等方面仍存在一定局限。用户应根据自身需求，选择适合的手机型号，同时注意合理使用，避免过度' additional_kwargs={'refusal': None} response_metadata={'token_usage': {'completion_tokens': 500, 'prompt_tokens': 25, 'total_tokens': 525, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_efad92c60b', 'id': 'chatcmpl-C7cnFf8eqgQAn9S5DJd3BOqd7Fw97', 'service_tier': None, 'finish_reason': 'length', 'logprobs': None} id='run--89c53853-e5ce-4473-baca-747a51d0ab3b-0' usage_metadata={'input_tokens': 25, 'output_tokens': 500, 'total_tokens': 525, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}}\n",
      "<class 'langchain_core.messages.ai.AIMessage'>\n"
     ]
    }
   ],
   "execution_count": 18
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
